package com.atguigu.atcrowdfunding.listener;

import com.atguigu.atcrowdfunding.bean.Permission;
import com.atguigu.atcrowdfunding.manager.service.PermissionService;
import com.atguigu.atcrowdfunding.util.Const;
import com.atguigu.atcrowdfunding.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author xzt
 * @create 2021-02-08 16:25
 */
public class StartSystemListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ServletContext servletContext = sce.getServletContext();
        String contextPath = servletContext.getContextPath();
        servletContext.setAttribute("APP_PATH",contextPath);

        WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);

        PermissionService permissionService = webApplicationContext.getBean(PermissionService.class);

        List<Permission> allPermission = permissionService.queryAllPermission();
        Set<String> allPermissionUrls = new HashSet<>();

        for (Permission permission : allPermission) {
            if(StringUtil.isNotEmpty(permission.getUrl())){
                allPermissionUrls.add("/"+permission.getUrl());
            }
        }

        servletContext.setAttribute(Const.ALL_PERMISSION_URI,allPermissionUrls);

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

    }
}
